package com.hero.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSONUtil;
import com.hero.domain.*;
import com.hero.minioutils.utils.MinioUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;

/**
 * @author yunfei
 * @date 2022年12月31日 16:21
 */
@Component
public class CoursePublishMinioListener {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioUtils minioUtils;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = "coursePublish", type = "fanout"),
            value = @Queue(name = "minioMQ")
    ))
    public void coursePublishRedisConsumer(String publishStr) {
        // 先根据课程id 生成课程的静态页面
        CoursePublish coursePublish = JSONUtil.toBean(publishStr, CoursePublish.class);
        // 拼凑一个Freemarker的模型数据
        // 把生成的静态页面保存到MINIO中
        genertatorHtml(coursePublish);
    }


    /**
     * 写消费者的时候
     * 脑袋中始终想着一件事  幂等性问题
     * 先确定当前这个操作是否是幂等性的
     * 如果是非幂等性的要保证幂等性操作
     */


    private void genertatorHtml(CoursePublish coursePublish) {
        try {
            //设置字符集
            configuration.setDefaultEncoding("utf-8");
            //加载模板文件
            // templates 这个名称是固定的
            Template template = null;
            template = configuration.getTemplate("course_template.ftl");


            String teachplan = coursePublish.getTeachplan();
            List<TeachplanDto> teachplanDtos = JSONUtil.toList(teachplan, TeachplanDto.class);

            // dto 是Freemarker模型数据
            CoursePreviewDto dto = new CoursePreviewDto();
            dto.setTeachplans(teachplanDtos);

            CourseBaseInfoDto courseBaseDto = new CourseBaseInfoDto();
            // courseBaseDto :  课程基本信息
            BeanUtil.copyProperties(coursePublish, courseBaseDto);
            // courseBaseDto :  课程营销信息
            String market = coursePublish.getMarket();
            CourseMarket courseMarket = JSONUtil.toBean(market, CourseMarket.class);
            BeanUtil.copyProperties(courseMarket, courseBaseDto, "id");
            dto.setCourseBase(courseBaseDto);

            //准备输出流对象，用于输出静态文件
            Writer writer = new FileWriter(coursePublish.getId() + ".html");

            //输出 freemarker的数据模型的类型只能是map或是JavaBean对象
            HashMap<String, Object> map = new HashMap<>();
            map.put("model", dto);
            template.process(map, writer);
            //关闭流
            writer.close();

            // Java读取文件  WEB环境下怎么读取
            // 项目的根目录  模块的根目录
            FileReader fileReader = new FileReader(FileUtil.getWebRoot().getParent() + "/"
                    + coursePublish.getId() + ".html");
            minioUtils.putObject("mediafiles", fileReader.readBytes(), "course/" + coursePublish.getId() + ".html",
                    "text/html", fileReader.readBytes().length);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}